package groovy.jmx.builder.modelmbean

import groovy.jmx.builder.node.MBeanNodeData
import javax.management.modelmbean.RequiredModelMBean




class ModelMBeanBuilder {
    public RequiredModelMBean build(MBeanNodeData data) {
        RequiredModelMBean bean
        if (data.description ||
                data.attributes.size() > 0 ||
                data.constructors.size() > 0 ||
                data.operations.size() > 0) {
            bean = buildModelMBean(data)
        } else {
            bean = buildModelMBean(data.object)
        }
        return bean
    }

    private RequiredModelMBean buildModelMBean(MBeanNodeData data) {
        RequiredModelMBean mbean = new RequiredModelMBean()
        if (data) {
            def info = new ModelMBeanCollector().collectMBeanInfo(data)
            mbean.setManagedResource(data.object, "ObjectReference")
            mbean.setModelMBeanInfo(info)
        }
        return mbean
    }

    private RequiredModelMBean buildModelMBean(def instance) {
        RequiredModelMBean mbean = new RequiredModelMBean()
        if (instance) {
            def info = new ModelMBeanCollector().collectMBeanInfo(instance)
            mbean.setManagedResource(instance, "ObjectReference")
            mbean.setModelMBeanInfo(info)
        }
        return mbean
    }
}